<!-- src/views/Chat.vue -->
<template>
  <div class="chat-view">
    <ConversationList />
    <div class="chat-container">
      <div v-if="chatStore.currentConversationId" class="chat-content">
        <div class="chat-header">
          <h2 class="chat-title">{{ chatStore.currentConversation?.title }}</h2>
        </div>
        <div class="chat-messages" ref="messagesContainer">
          <div v-for="(message, index) in chatStore.currentMessages" :key="index" :class="['message', message.role]">
            <div class="avatar">
              {{ message.role === 'user' ? '👤' : '🤖' }}
            </div>
            <div class="content">
              <div class="text" :class="{ 'typing': isTyping(message) && index === chatStore.currentMessages.length - 1 }">
                <template v-if="message.role === 'user'">
                  {{ message.content }}
                </template>
                <MarkdownRenderer v-else :content="message.content" />
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <el-input v-model="userInput" type="textarea" :rows="3" placeholder="请输入您的问题..." resize="none"
            @keydown.enter.prevent="handleSend" :disabled="chatStore.isGenerating" />
          <div class="button-group">
            <template v-if="!chatStore.isGenerating">
              <el-button type="primary" :loading="chatStore.loading" :disabled="chatStore.loading || !userInput.trim()"
                @click="handleSend">发送</el-button>
              <el-button v-if="chatStore.canContinue" type="success" @click="handleContinue">继续生成</el-button>
            </template>
            <el-button v-else type="warning" @click="handleStop">停止生成</el-button>
          </div>
        </div>
      </div>
      <div v-else class="empty-state">
        <el-empty description="选择一个会话或创建新会话">
          <el-button type="primary" @click="chatStore.createNewConversation">
            创建新会话
          </el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { useChatStore } from '../store/chat'
// import { storeToRefs } from 'pinia'
import MarkdownRenderer from '../components/MarkdownRenderer.vue'
import ConversationList from '../components/ConversationList.vue'

const chatStore = useChatStore()
const userInput = ref('')
const messagesContainer = ref<HTMLElement | null>(null)
const handleStop = () => {
  console.log('Stop button clicked')
  chatStore.stopGeneration()
}
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}
const handleContinue = async () => {
  try {
    await chatStore.continueGeneration()
  } catch (error: any) {
    ElMessage.error({
      message: error.message || '继续生成失败，请重试',
      duration: 5000,
      showClose: true,
    })
  }
  await scrollToBottom()
}
const isTyping = (message: any) => {
  return message.role === 'assistant' && chatStore.loading
}

const handleSend = async () => {
  if (!userInput.value.trim()) {
    ElMessage.warning('请输入内容')
    return
  }

  const currentInput = userInput.value
  userInput.value = ''

  try {
    await chatStore.sendMessage(currentInput)
  } catch (error: any) {
    ElMessage.error({
      message: error.message || '发送消息失败，请重试',
      duration: 5000,
      showClose: true,
    })
  }

  await scrollToBottom()
}

// 监听消息变化，自动滚动到底部
watch(() => chatStore.currentMessages, () => {
  scrollToBottom()
}, { deep: true })

onMounted(() => {
  if (!chatStore.currentConversationId) {
    chatStore.createNewConversation()
  }
})
</script>

<style scoped lang="scss">
.chat-view {
  display: flex;
  height: 100vh;
  background: var(--bg-primary);
}

.chat-container {
  flex: 1;
  margin-left: 260px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 16px 24px;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
  position: sticky;
  top: 0;
  z-index: 10;
  flex-shrink: 0;

  .chat-title {
    margin: 0;
    font-size: 1.25rem;
    font-weight: 600;
    color: var(--text-primary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  
  .message {
    display: flex;
    margin-bottom: 24px;
    gap: 16px;

    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: var(--accent-color);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      flex-shrink: 0;
    }

    .content {
      // flex: 1;
      max-width: calc(100% - 56px);

      .text {
        padding: 12px 16px;
        background: var(--bg-secondary);
        border-radius: 8px;
        color: var(--text-primary);
        line-height: 1.5;
        
        &.typing::after {
          content: '▋';
          animation: blink 1s step-start infinite;
        }
      }
    }

    &.user {
      flex-direction: row-reverse;
      .avatar {
        background: var(--user-avatar-bg);
      }
      .text {
        background: var(--accent-color);
        color: white;
      }
    }
  }
}

.chat-input {
  padding: 24px;
  background: var(--bg-secondary);
  border-top: 1px solid var(--border-color);
  flex-shrink: 0;

  .button-group {
    display: flex;
    gap: 8px;
    margin-top: 12px;
    justify-content: flex-end;
  }
}

.empty-state {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}


// // 添加主题切换过渡效果
// ::v-deep(*) {
//   transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
// }

// @keyframes typing {

//   0%,
//   100% {
//     transform: translateY(0);
//   }

//   50% {
//     transform: translateY(-4px);
//   }
// }

// .text {
//   &.typing {
//     border-right: 2px solid var(--accent-color);
//     animation: blink 0.8s step-end infinite;
//   }
// }

// @keyframes blink {

//   from,
//   to {
//     border-color: transparent;
//   }

//   50% {
//     border-color: #409eff;
//   }
// }
</style>